package com.xtianzhuang.www.study2019.utils;


import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.velocity.VelocityContext;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;


public class MybatisUtils {

	// generatorConfig模板路径
	// private static String generatorConfig_vm =
	// "/Users/xtian.zhuang/code-space/eclipse-workspace/study2019/src/main/resources/template/generatorConfig.vm";
	// public static final String generatorConfig_XML =
	// "/Users/xtian.zhuang/code-space/eclipse-workspace/study2019/src/main/resources/template/generatorConfig.xml";
	private static String generatorConfig_vm = "C:\\project\\mine\\study2019\\src\\main\\resources\\template\\generatorConfig.vm";
	public static final String generatorConfig_XML = "C:\\project\\mine\\study2019\\src\\main\\resources\\template\\generatorConfig.xml";
	/**
	 * 
	 * @param generatorInfo
	 * @param lastInsertIdTables
	 * @throws Exception
	 */
	public static void generator(GeneratorInfo generatorInfo, Map<String, String> lastInsertIdTables, String tablePre)
			throws Exception {
		String generatorConfigXml = generatorXML(generatorInfo, lastInsertIdTables, tablePre);
		generatorSQL(generatorConfigXml);
	}

	/**
	 * 利用vm模板生产xml
	 * @param generatorInfo
	 * @param lastInsertIdTables
	 * @return
	 */
	public static String generatorXML(GeneratorInfo generatorInfo, Map<String, String> lastInsertIdTables,
			String tablePre) {
		String generatorConfigXml = generatorConfig_XML;
		System.out.println(generatorConfigXml);
		// 查询所有表名
		String table_sql = "SELECT table_name FROM INFORMATION_SCHEMA.TABLES WHERE table_schema = '"
				+ generatorInfo.getDatabase() + "'";
		if (StringUtils.isNotEmpty(tablePre)) {
			table_sql += " and table_name like '" + tablePre + "'";
		}
		System.out.println("========== 开始生成generatorConfig.xml文件 ==========");
		List<Map<String, Object>> tables = new ArrayList<>();
		try {
			VelocityContext context = new VelocityContext();
			Map<String, Object> table;
			// 查询定制前缀项目的所有表
			JdbcUtil jdbcUtil = new JdbcUtil(generatorInfo.getJdbcDriver(), generatorInfo.getJdbcUrl(),
					generatorInfo.getUserName(), generatorInfo.getPassword());
			List<Map> table_result = jdbcUtil.selectByParams(table_sql, null);
			for (Map map : table_result) {
				System.out.println(map.get("TABLE_NAME"));
				table = new HashMap<>(2);
				table.put("table_name", map.get("TABLE_NAME"));
				table.put("model_name", StringUtil.lineToHump(ObjectUtils.toString(map.get("TABLE_NAME"))));
				tables.add(table);
			}
			jdbcUtil.release();
			context.put("tables", tables);
			context.put("generator_javaModelGenerator_targetPackage", generatorInfo.getEntityPath());
			context.put("generator_sqlMapGenerator_targetPackage", generatorInfo.getSqlPath());
			context.put("generator_javaClientGenerator_targetPackage", generatorInfo.getDaoPath());
			context.put("targetProject", generatorInfo.getTargetProject());
			context.put("generator_jdbc_password", generatorInfo.getPassword());
			context.put("last_insert_id_tables", lastInsertIdTables);
			VelocityUtil.generate(generatorConfig_vm, generatorConfigXml, context);
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("========== 结束生成generatorConfig.xml文件 ==========");
		return generatorConfigXml;
	}

	/**
	 * 利用xml生成dao，entity，xml
	 * @param generatorConfigUrl
	 * @throws Exception
	 */
	public static void generatorSQL(String generatorConfigUrl) throws Exception {
		System.out.println("========== 开始运行MybatisGenerator ==========");
		List<String> warnings = new ArrayList<>();
		File configFile = new File(generatorConfigUrl);
		ConfigurationParser cp = new ConfigurationParser(warnings);
		Configuration config = cp.parseConfiguration(configFile);
		DefaultShellCallback callback = new DefaultShellCallback(true);
		MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
		myBatisGenerator.generate(null);
		for (String warning : warnings) {
			System.out.println(warning);
		}
		System.out.println("========== 结束运行MybatisGenerator ==========");

	}

	// 递归删除非空文件夹
	public static void deleteDir(File dir) {
		if (dir.isDirectory()) {
			File[] files = dir.listFiles();
			for (int i = 0; i < files.length; i++) {
				deleteDir(files[i]);
			}
		}
		dir.delete();
	}

}
